/*
Mem.Get("key"); //获取值
Mem.Put("key","值支持对象更新部分","时间"); //更新值 可以只更新时间 时间0不过期 值不存在返回 false
Mem.Set(key,value,"时间");//设置或者新增值 
Mem.Add(key,"默认值1",time);//增加值  支持时间过期
Mem.Cut(key,"默认值1",time);//减少值 支持时间过期
Mem.Del(key);//删除
Mem.Flush(key);// key 为空清理全部  不为空删除包含关键词
*/
var Kuo_Cache_Mysql = {
    DB:null,
    Table:"memcached",
    //配置参数 Mode("Tools").Time()
    Config:async (config)=>{
        if(config && config.dbname){
            Kuo_Cache_Mysql.Table = MYSQLconfig.prefix + config.dbname;
        }
        
        if(config && config.Table && config.Table != ""){
            Kuo_Cache_Mysql.Table =  config.Table;
        }

        if(config && config.Server&& config.Server != "" && global[config.Server]){
            Kuo_Cache_Mysql.DB = global[config.Server];
        }else{
            Kuo_Cache_Mysql.DB = DB;
        }
        return Kuo_Cache_Mysql;
    },Get:async (key)=>{
        /*获取数据 */
        return new Promise((resolve, reject) => {
            Kuo_Cache_Mysql.DB.query("SELECT name,keval,atime FROM ??  Where `name` = ? LIMIT 1",[ Kuo_Cache_Mysql.Table ,key], function (error, results) { 
                if(error){
                    resolve(null);
                    return false;
                }
                if(results.length < 1){
                    resolve(null);
                    return false;
                }
                var data = results.pop();
                if(data['atime'] > 0 && Mode("Tools").Time() > data['atime']){
                    Kuo_Cache_Mysql.Del(key);
                    resolve(null);
                    return true;
                }
                resolve( JSON.parse(data['keval']) );
                return true;
            });
        });

    },Put:async (key,value,time)=>{
        /*更新*/
        if(!key){
            return false;
        }
        if(!time){
            time = 0;
        }
        if(value){
            var zhi = await Kuo_Cache_Mysql.Get(key);
            if(zhi && typeof(zhi) == typeof(value)){
                for(var k in value){
                    zhi[k] = value[k];
                }
                value = zhi;
            }
        }
        return await Kuo_Cache_Mysql.Set(key,value,time);
    },Set:async (key,value,time)=>{
        /**设置值  */
        if(!key){
            return false;
        }
        if(!time){
            time = 0;
        }
        if(time > 0){
            time += Mode("Tools").Time();
        }

        if(value){
            var  $sql  = "UPDATE ?? SET `keval` = ?,`atime` = ? WHERE `name` = ?";
            var $sqldata = [ Kuo_Cache_Mysql.Table , JSON.stringify(value), time,key];
        }else{
            var $sql  = "UPDATE ?? SET `atime` = ? WHERE `name` = ?";
            var $sqldata = [ Kuo_Cache_Mysql.Table , time,key];
        }
        return new Promise((resolve, reject) => {
            Kuo_Cache_Mysql.DB.query($sql,$sqldata, function (error, results) {
                if(error || !results ||  results.affectedRows < 1){
                    $sql  = "INSERT INTO ?? (`keval`,`atime`,`name`) VALUES (?,?,? );";
                    $sqldata = [ Kuo_Cache_Mysql.Table , JSON.stringify(value), time,key];

                    Kuo_Cache_Mysql.DB.query($sql,$sqldata, function (error, results) { 
                        if(error ){
                            resolve(false);
                            return false;
                        }
                        if(results.affectedRows < 1){
                            resolve(false);
                            return false;
                        }
                        resolve(true);
                        return true;
                    });
                }
                resolve(true);
                return true;
            });
        });
      

    },Add:async (key,value,time)=>{
        /* 增加 */
        if(!time){
            time = 0;
        }
        if(!value){
            value = 1;
        } 
        var zhi = await Kuo_Cache_Mysql.Get(key);
        if(!zhi){
            zhi = 0;
        }
        if(isNaN(zhi)){
            zhi = 0;
        }
        zhi = Number(zhi*1);
        zhi += Number(value);
        await Kuo_Cache_Mysql.Set(key,zhi,time);
        return zhi;

    },Cut:async (key,value,time)=>{
        /* 减少 */
        if(!time){
            time = 0;
        }
        if(!value){
            value = 1;
        } 
        var zhi = await Kuo_Cache_Mysql.Get(key);
        if(!zhi){
            zhi = 0;
        }
        if(isNaN(zhi)){
            zhi = 0;
        }
        zhi = Number(zhi*1);
        zhi -= Number(value);
        await Kuo_Cache_Mysql.Set(key,zhi,time);
        return zhi;

    },Del:async(key)=>{
        /*删除缓存 */
        if(!key){
            return false;
        }
        return new Promise((resolve, reject) => {
            Kuo_Cache_Mysql.DB.query("DELETE FROM ?? WHERE `name` = ? ",[Kuo_Cache_Mysql.Table ,key], function (error, results) {
                if(error ){
                    resolve(false);
                    return false;
                }
                if(results.affectedRows < 1){
                    resolve(false);
                    return false;
                }
                resolve(true);
                return true;
            });
        });

    },Total:async()=>{
        /*统计数据 */

        return new Promise((resolve, reject) => {
            Kuo_Cache_Mysql.DB.query(`SELECT count(*) as count FROM ?? `,[ Kuo_Cache_Mysql.Table ], function (error, results) { 
                if(error){
                    resolve(0);
                    return 0;
                }
                var shuju = results.pop();
                resolve(Number(shuju['count']));
                return Number(shuju['count']);
            });
        });
        
    },Flush:async(key)=>{
        /*清空数据 */
        if(key){
            var $sql = "DELETE  FROM ??  WHERE `name` LIKE ?";
            var $sqldata = [Kuo_Cache_Mysql.Table,'%'+key+'%'];
        }else{
            var $sql = "DELETE  FROM ?? ";
            var $sqldata = [Kuo_Cache_Mysql.Table];
        }
        return new Promise((resolve, reject) => {
            Kuo_Cache_Mysql.DB.query($sql,$sqldata, function (error, results) {
                if(error ){
                    resolve(false);
                    return false;
                }
                if(results.affectedRows < 1){
                    resolve(false);
                    return false;
                }
                resolve(true);
                return true;
            });
        });
    },Save:()=>{
        /* 预留接口存档 */

    }
};
module.exports = Kuo_Cache_Mysql;